package com.ytq.secutiry.config.filter;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author yuantongqin
 * desc: token 验证过滤器
 * 2020-09-30
 */
public class JwtFilter extends BasicAuthenticationFilter {

    public JwtFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }



    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = httpServletRequest.getRequestURI();
        PathMatcher matcher = new AntPathMatcher();
        List<String> urls = new ArrayList<>();
        urls.add("/login");
        urls.add("/formLogin");
        boolean flag = false;
        for (String url : urls) {
            if(matcher.match(url,requestURI)){
                flag = true;
                break;
            }
        }
        // 需要拦截的接口
        if(!flag){
            // 判断这个url需要需要授权验证
            String accessToken = httpServletRequest.getHeader("accessToken");
            if(StringUtils.isEmpty(accessToken) || !Objects.equals(accessToken,"1111")){
                System.out.println("token验证失败");
                return ;
            }
        }
        // 不需要验证token
        filterChain.doFilter(httpServletRequest,httpServletResponse);
        System.out.println("过滤器处理完成");
    }

}
